package org.tooyoung.fourone.live.activitys;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.os.PersistableBundle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.style.BackgroundColorSpan;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.sample.BiliDanmukuParser;
import com.squareup.picasso.Picasso;

import io.vov.vitamio.Vitamio;
import io.vov.vitamio.widget.VideoView;

import master.flame.danmaku.controller.DrawHandler;
import master.flame.danmaku.danmaku.loader.ILoader;
import master.flame.danmaku.danmaku.loader.IllegalDataException;
import master.flame.danmaku.danmaku.loader.android.DanmakuLoaderFactory;
import master.flame.danmaku.danmaku.model.BaseDanmaku;
import master.flame.danmaku.danmaku.model.DanmakuTimer;
import master.flame.danmaku.danmaku.model.IDisplayer;
import master.flame.danmaku.danmaku.model.android.DanmakuContext;
import master.flame.danmaku.danmaku.model.android.Danmakus;
import master.flame.danmaku.danmaku.model.android.SpannedCacheStuffer;
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser;
import master.flame.danmaku.danmaku.parser.IDataSource;
import master.flame.danmaku.ui.widget.DanmakuView;

import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import rx.Observable;
import rx.Observer;
import rx.Scheduler;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.tooyoung.fourone.R;
import org.tooyoung.fourone.live.ImageUtils.CircleImage;
import org.tooyoung.fourone.live.adapters.MyFanListAdapter;
import org.tooyoung.fourone.live.clients.networkTool;
import org.tooyoung.fourone.live.models.Fan;
import org.tooyoung.fourone.live.models.FanData;
import org.tooyoung.fourone.live.models.Presenter;
import org.tooyoung.fourone.live.models.PresnetData;
import org.tooyoung.fourone.live.models.Room;

import java.io.InputStream;
import java.util.HashMap;
import java.util.IllegalFormatCodePointException;
import java.util.List;

public class PlayActivity extends AppCompatActivity implements View.OnClickListener {

   private VideoView vv;
    private Room room;
    private RecyclerView recycler;
    private List<Fan> list;
    private MyFanListAdapter myFanListAdapter;
    private ImageView live_zhu_iv;
    private TextView live_zhu_tv;
    private ImageView tuichu;
    private DanmakuView mDanmakuView;
    private DanmakuContext mDanmakuContext;
    private BaseDanmakuParser mParser;
    private ImageView gift;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Vitamio.isInitialized(this);
        setContentView(R.layout.activity_play);
        Intent intent = getIntent();
        if (intent != null) {
            room=intent.getParcelableExtra("data");
        }
        live_zhu_iv = (ImageView) findViewById(R.id.live_zhu_iv);
        live_zhu_tv = (TextView) findViewById(R.id.live_zhu_tv);
        tuichu = (ImageView) findViewById(R.id.live_tuichu);
        mDanmakuView = (DanmakuView) findViewById(R.id.danmaview);
        mDanmakuContext = DanmakuContext.create();
        DoSetting();
        tuichu.setOnClickListener(this);
        recycler = (RecyclerView) findViewById(R.id.live_header_RecyclerView);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        recycler.setLayoutManager(linearLayoutManager);
        myFanListAdapter = new MyFanListAdapter(this,list);
        recycler.setAdapter(myFanListAdapter);
        getFanData();
        vv = (VideoView) findViewById(R.id.vv);
        vv.setVideoPath(room.getUrl());
        vv.start();
        getPresenterData();
        gift = (ImageView) findViewById(R.id.live_gift);
        gift.setOnClickListener(this);


    }
    public void addGiftPop()
    {
        View view = LayoutInflater.from(this).inflate(R.layout.giftpop, null, false);
        final PopupWindow popupWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT,250 , true);
        popupWindow.showAtLocation(view, Gravity.BOTTOM,0,0);
        //popupWindow.setAnimationStyle(Animation.);
        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (popupWindow!=null && popupWindow.isShowing())
                {
                    popupWindow.dismiss();
                }
                return false;
            }
        });
    }
    public void getFanData()
    {
        Retrofit.Builder builder = new Retrofit.Builder();
        Retrofit retrofit = builder.baseUrl("http://api.fenbei.com/")
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io()))
                .build();
        networkTool tool = retrofit.create(networkTool.class);
        Observable<FanData> observable = tool.getFanData(1, 100000009, room.getRoomid(), 1);
        observable.observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<FanData>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(PlayActivity.this, "网络错误异常，请检查网络", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onNext(FanData fanData) {
                        if (fanData != null) {
                            int size = fanData.getData().getViewers().size();
                            Log.d("33333", "onNext: "+room.getRoomid());
                            list = fanData.getData().getViewers();
                            if (list != null) {
                                myFanListAdapter=new MyFanListAdapter(getApplicationContext(),list);
                                recycler.setAdapter(myFanListAdapter);
                                myFanListAdapter.notifyDataSetChanged();

                            }
                        }

                    }
                });

    }
    public void getPresenterData()
    {
        Retrofit.Builder builder = new Retrofit.Builder();
        Retrofit retrofit = builder.baseUrl("http://api.fenbei.com/")
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io()))
                .build();
        networkTool tool = retrofit.create(networkTool.class);
        final Observable<PresnetData> presentData = tool.getPresentData(room.getId(),room.getRoomid());
        presentData.observeOn(AndroidSchedulers.mainThread())
                   .subscribe(new Observer<PresnetData>() {
                       @Override
                       public void onCompleted() {

                       }

                       @Override
                       public void onError(Throwable e) {
                           Toast.makeText(PlayActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                       }

                       @Override
                       public void onNext(PresnetData p) {
                           if (p!= null) {
                               Presenter user = p.getData().getUser();
                               String headimg = user.getHeadimg();
                               Log.d("22222", "onNext: "+ headimg);
                               Picasso.with( live_zhu_iv .getContext())
                                       .load(room.getHeadimg())
                                       .config(Bitmap.Config.RGB_565)
                                       .placeholder(R.mipmap.default_head_light)
                                       .error(R.mipmap.default_head_light)
                                       .transform(new CircleImage())
                                       .into(live_zhu_iv);
                               live_zhu_tv.setText(room.getNickname()+"\n"+"粉丝"+room.getPlaynum());
                           }
                       }
                   });
    }

    public void DoSetting()
    {

        //设置显示弹幕的最大显示行数
        HashMap<Integer, Integer> maxLinesPair = new HashMap<>();
        maxLinesPair.put(BaseDanmaku.TYPE_SCROLL_RL,3);//滚动弹幕最大显示3行
        //设置是否禁止重叠
        HashMap<Integer, Boolean> overlappingEnablePair = new HashMap<>();
        overlappingEnablePair.put(BaseDanmaku.TYPE_SCROLL_LR,true);
        overlappingEnablePair.put(BaseDanmaku.TYPE_FIX_BOTTOM,true);//是否固定在底部



        mDanmakuContext.setDanmakuStyle(IDisplayer.DANMAKU_STYLE_STROKEN,3)//设置描边样式
                .setDuplicateMergingEnabled(false)//设置是否启动合并并启用重复弹幕
                .setScrollSpeedFactor(1.2f)//设置单目滚动速度系数，只对滚动弹幕有效
                .setScaleTextSize(0.8f)
                .setMaximumLines(maxLinesPair)////设置显示弹幕的最大显示行数
                .preventOverlapping(overlappingEnablePair);//设置防弹幕重叠，null为允许重叠
                //.setCacheStuffer(new BackgroundCacheStuffer());
        // 图文混排使用SpannedCacheStuffer
        // 设置缓存绘制填充器，默认使用{@link SimpleTextCacheStuffer}
        // 只支持纯文字显示, 如果需要图文混排请设置{@link SpannedCacheStuffer}
        // 如果需要定制其他样式请扩展{@link SimpleTextCacheStuffer}
        // |{@link SpannedCacheStuffer}

        if (mDanmakuView != null) {
            //创建解析器对象，从raw资源目录下解析comments.xml文本
            mParser=createParser(getApplicationContext().getResources().openRawResource(R.raw.comments));
            mDanmakuView.setCallback(new DrawHandler.Callback() {
                @Override
                public void prepared() {
                    mDanmakuView.start();
                }

                @Override
                public void updateTimer(DanmakuTimer timer) {

                }

                @Override
                public void danmakuShown(BaseDanmaku danmaku) {

                }

                @Override
                public void drawingFinished() {

                }
            } );

            mDanmakuView.prepare(mParser, mDanmakuContext);
            mDanmakuView.showFPS(false); //是否显示FPS
            mDanmakuView.enableDanmakuDrawingCache(true);
        }
    }
    /**
     * 创建解析器对象，解析输入流
     *
     *  DanmakuLoaderFactory.create(DanmakuLoaderFactory.TAG_BILI) //xml解析
     *  DanmakuLoaderFactory.create(DanmakuLoaderFactory.TAG_ACFUN) //json文件格式解析
     * @param stream
     * @return
     */
    private BaseDanmakuParser createParser(InputStream stream) {

        if (stream == null) {
            return new BaseDanmakuParser() {

                @Override
                protected Danmakus parse() {
                    return new Danmakus();
                }
            };
        }

        ILoader loader = DanmakuLoaderFactory.create(DanmakuLoaderFactory.TAG_BILI);

        try {
            loader.load(stream);
        } catch (IllegalDataException e) {
            e.printStackTrace();
        }
        BaseDanmakuParser parser = new BiliDanmukuParser();
        IDataSource<?> dataSource = loader.getDataSource();
        parser.load(dataSource);
        return parser;

    }

    /**
     * 添加文本弹幕
     * @param islive
     */
    private void addDanmaku(boolean islive) {
        BaseDanmaku danmaku = mDanmakuContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL);
        if (danmaku == null || mDanmakuView == null) {
            return;
        }

        danmaku.text = "这是一条弹幕" + System.nanoTime();
        danmaku.padding = 5;
        danmaku.priority = 0;  //0 表示可能会被各种过滤器过滤并隐藏显示 //1 表示一定会显示, 一般用于本机发送的弹幕
        danmaku.isLive = islive; //是否是直播弹幕
        // danmaku.time = mDanmakuView.getCurrentTime() + 1200; //显示时间
        danmaku.textSize = 25f * (mParser.getDisplayer().getDensity() - 0.6f);
        danmaku.textColor = Color.RED;
        danmaku.textShadowColor = Color.WHITE; //阴影/描边颜色
        danmaku.borderColor = Color.GREEN; //边框颜色，0表示无边框
        mDanmakuView.addDanmaku(danmaku);

    }


    /**
     *  添加图文混排弹幕
     * @param islive
     */
    private void addDanmaKuShowTextAndImage(boolean islive) {
        BaseDanmaku danmaku = mDanmakuContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL);
        Drawable drawable = getResources().getDrawable(R.mipmap.ic_launcher);
        drawable.setBounds(0, 0, 100, 100);
        SpannableStringBuilder spannable = createSpannable(drawable);
        danmaku.text = spannable;
        danmaku.padding = 5;
        danmaku.priority = 1;  // 一定会显示, 一般用于本机发送的弹幕
        danmaku.isLive = islive;
        //danmaku.time = mDanmakuView.getCurrentTime() + 1200;
        danmaku.textSize = 25f * (mParser.getDisplayer().getDensity() - 0.6f);
        danmaku.textColor = Color.RED;
        danmaku.textShadowColor = 0; // 重要：如果有图文混排，最好不要设置描边(设textShadowColor=0)，否则会进行两次复杂的绘制导致运行效率降低
        danmaku.underlineColor = Color.GREEN;
        mDanmakuView.addDanmaku(danmaku);
    }

    /**
     * 创建图文混排模式
     * @param drawable
     * @return
     */
    private SpannableStringBuilder createSpannable(Drawable drawable) {
        String text = "bitmap";
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(text);
        ImageSpan span = new ImageSpan(drawable);//ImageSpan.ALIGN_BOTTOM);
        spannableStringBuilder.setSpan(span, 0, text.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        spannableStringBuilder.append("图文混排");
        spannableStringBuilder.setSpan(new BackgroundColorSpan(Color.parseColor("#8A2233B1")), 0, spannableStringBuilder.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        return spannableStringBuilder;
    }
    /**
     * 自定义弹幕背景和边距
     */
    private static class BackgroundCacheStuffer extends SpannedCacheStuffer {
        // 通过扩展SimpleTextCacheStuffer或SpannedCacheStuffer个性化你的弹幕样式
        final Paint paint = new Paint();


//        @Override
//        public void measure(BaseDanmaku danmaku, TextPaint paint) {
//            danmaku.padding = 10;  // 在背景绘制模式下增加padding
//            super.measure(danmaku, paint);
//        }


        @Override
        public void drawBackground(BaseDanmaku danmaku, Canvas canvas, float left, float top) {
            paint.setColor(Color.TRANSPARENT);  //弹幕背景颜色
            canvas.drawRect(left + 2, top + 2, left + danmaku.paintWidth - 2, top + danmaku.paintHeight - 2, paint);
        }


        @Override
        public void drawStroke(BaseDanmaku danmaku, String lineText, Canvas canvas, float left, float top, Paint paint) {
            // 禁用描边绘制
        }
    }
    /**
     * 退出时释放资源
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDanmakuView != null) {
            // dont forget release!
            mDanmakuView.release();
            mDanmakuView = null;
        }
    }
    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.live_tuichu:
                finish();
                break;
            case R.id.live_gift:
                addGiftPop();
                break;
        }
    }
}
